﻿using System;

using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;

namespace Christian.Helle.PocketNews.PocketPC.Controls
{
    /// <summary>
    /// A Helper object to adjus the sizes of controls based on the DPI.
    /// </summary>
    public class Dpi
    {
        /// <summary>
        /// Returns TRUE if the Device is a High DPI device
        /// </summary>
        public static bool IsHighDpi
        {
            get
            {
                Rectangle rect = Screen.PrimaryScreen.WorkingArea;
                if ((rect.Width + rect.Height) > 560)
                    return true;
                else return false;
            }
        }

        [DllImport("coredll.dll")]
        private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);

        private const int LOGPIXELSX = 88;
        private static int dpi = GetDeviceCaps(IntPtr.Zero, LOGPIXELSX);

        /// <summary>
        /// Get the Device's DPI
        /// </summary>
        public static int DeviceCaps
        {
            get { return dpi; }
        }

        /// <summary>
        /// Adjust the sizes of controls to account for the DPI of the device.		
        /// </summary>
        /// <param name="parent">The parent node of the tree of controls to adjust.</param>
        public static void AdjustAllControls(Control parent)
        {
            if (dpi == 96)
                return;
            foreach (Control child in parent.Controls) {
                AdjustControl(child);
                AdjustAllControls(child);
            }
        }

        /// <summary>
        /// Adjust the sizes of controls to account for the DPI of the device.		
        /// </summary>
        /// <param name="control">The parent node of the tree of controls to adjust.</param>
        public static void AdjustControl(Control control)
        {
            control.Bounds = new Rectangle(
                control.Left * dpi / 96,
                control.Top * dpi / 96,
                control.Width * dpi / 96,
                control.Height * dpi / 96);
        }

        /// <summary>
        /// Scale a coordinate to account for the dpi.
        /// </summary>
        /// <param name="x">The number of pixels at 96 dpi</param>
        /// <returns></returns>
        public static int Scale(int x)
        {
            return x * dpi / 96;
        }
    }
}
